import { defineComponent, PropType } from 'vue';
import { ElButton, ElTag } from "element-plus";
import './table-props-editor.scss'
import { VisualEditorProps } from '@/packages/visual-editor.props';
import { useModel } from '@/packages/utils/useModel';
import { TablePropEditService } from './table-prop-editor.service';

export const TablePropEditor = defineComponent({
  props: {
    modelValue: { type: Array as PropType<any[]> },
    config: { type: Object as PropType<VisualEditorProps>, required: true },
  },
  emits: {
    'update:modelValue': (val?: object[]) => true,
    'change': (val?: object[]) => true,
  },
  setup(props, ctx) {

    const model = useModel(() => props.modelValue, val => ctx.emit('update:modelValue', val))

    const openEdit = async () => {
        const newData = await TablePropEditService({
            config: props.config,
            data: props.modelValue,
        })
        ctx.emit('update:modelValue', newData)
        ctx.emit('change', newData)
    }

    return () => {
      return (
        <div class="table-props-editor" {...{onClick:openEdit} as any}>
          {(!model.value || model.value.length < 1) && <ElButton icon="el-icon-plus" size="mini">添加</ElButton>}
          {(model.value || []).map((item,index) => (
            <ElTag key={index} size="small">
              { item[props.config.table!.showKey]}
            </ElTag>
          ))}
        </div>
      )
    }
  },
})